const readline=require('readline')
const request=require('request')
const path=require('path')
const fs=require('fs')
const iconv=require('iconv-lite')

let page=0

const question=(txt)=>{
  return new Promise((resolve,reject)=>{
      let rl=readline.createInterface({
          input:process.stdin,
          output:process.stdout
      });

      rl.question(txt,(txt)=>{
          rl.close()
          resolve(txt)
      })
  })
}

const sleep=function(delayS){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      resolve(true)
    },delayS)
  })
}

async function main(){
  let goodId=parseInt(await question('请输入商品编号：'))

  if (isNaN(goodId)){
    console.log('请输入正确的商品编号...')
    process.exit()
  }

  console.log('商品编号为：'+goodId)
  dgFunc(goodId)
}

async function dgFunc(goodId){
  await sleep(500)
  console.log('page '+page)
  let txt=await getComments(goodId,page).catch((err)=>{
    console.log('net',err)
  })
  if (txt){
    writeRes(goodId,txt)
    page++
    dgFunc(goodId)
  }else{
    console.log('end')
    process.exit()
  }

}

async function mainTest(){
  const id=100006897507
  let txt=await getComments(id,0)
  // console.log(txt)
  writeRes(id,txt)
}

// eval function 
function fetchJSON_comment98(obj){
  return obj
}

function getComments(id,page){
  return new Promise((resolve,reject)=>{
    // 差评 score 1
    let url=`https://club.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98&productId=${id}&score=1&sortType=5&page=${page}&pageSize=10&isShadowSku=0&fold=1`
    let ress=null
    let rtxt=''
    request({
      encoding:null,
      url:url,
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36'
      }
    },(err,res,body)=>{
      if (err){
        reject(err)
      }

      ress=eval(iconv.decode(body,'GBK'))
      // console.log('net',ress)
      if (ress && ress.comments!==void 0){
        for (let item of ress.comments){
          rtxt+=item.content+'\r\n'
        }
        resolve(rtxt)
      }else{
        resolve('')
      }
      
    })
  })
}

function writeRes(id,txt){
  // console.log(txt)
  fs.writeFileSync(id+'.txt',txt,{
    encoding:'utf8',
    flag:'as+'
  },(err)=>{
    console.log(err)
  })
}


main()